package com.my.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.entity.Student;
import com.my.entity.UserMenu;
import com.my.service.StudentService;
import com.my.service.UserMenuService;
import com.my.util.Rest;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@CrossOrigin
public class StudentController {

    @Resource
    private StudentService service;

    @Resource
    private UserMenuService umService;

    public static final Long[] STUDENT_MENU = { 11L, 12L, 13L };

    @PostMapping("student/get")
    public Rest get(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize, @RequestBody Student student) {
        return Rest.ok().setData("page", service.getPage(new Page<>(pageNo, pageSize), student));
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("students")
    public Rest add(@RequestBody Student student) {
        if(service.save(student.setPassword(StrUtil.isNotBlank(student.getPassword()) ? SecureUtil.md5(student.getPassword()) : SecureUtil.md5("123456")))) {
            for (Long i : STUDENT_MENU) {
                umService.save(new UserMenu().setUserId(student.getId()).setType(3).setMenuId(i));
            }
            return Rest.ok("添加成功！");
        }
        return Rest.err("添加失败！");
    }

    @PutMapping("students")
    public Rest edit(@RequestBody Student student) {
        if(StrUtil.isBlank(student.getPassword())) {
            student.setPassword(null);
        }else {
            student.setPassword(SecureUtil.md5(student.getPassword()));
        }
        if(service.updateById(student)) {
            return Rest.ok("修改成功！");
        }
        return Rest.err("修改失败！");
    }

    @GetMapping("student/repeat")
    public Rest repeat(@RequestParam String username, @RequestParam(defaultValue = "-1") Long id) {
        QueryWrapper<Student> qw = new QueryWrapper<Student>().eq("username", username);
        if(id != -1) {
            qw.ne("id", id);
        }
        return Rest.ok().setData("flag", service.getOne(qw) != null);
    }

    @PostMapping("student/status")
    public Rest status(@RequestBody Student student) {
        if(service.updateById(student)) {
            return Rest.ok("状态修改成功！");
        }
        return Rest.err("状态修改失败！");
    }

    @DeleteMapping("students")
    public Rest del(Long id) {
        if(service.removeById(id)) {
            umService.remove(new QueryWrapper<UserMenu>().eq("user_id", id).eq("type", 3));
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

}
